package com.wstuo.common.security.service;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.bpm.api.IBPS;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IOrganizationServicesDAO;
import com.wstuo.common.security.dao.IRoleDAO;
import com.wstuo.common.security.dao.IServiceTimeDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.OrganizationServices;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.ServiceTime;
import com.wstuo.common.util.AppliactionBaseListener;

/**
 * 服务机构业务类
 * 
 */
public class OrganizationServicesService implements IOrganizationServicesService {
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private IOrganizationServicesDAO organizationServicesDAO;
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IRoleDAO roleDAO;
	@Autowired
	private IServiceTimeDAO serviceTimeDAO;

	/**
	 * 保存服务机构.
	 * 
	 * @param dto
	 *            机构DTO：OrganizationDTO
	 */
	@Transactional()
	public void saveOrganizationServices(OrganizationDTO dto) {
		OrganizationServices ser = new OrganizationServices();

		ser.setOrgName(dto.getOrgName());
		ser.setOfficeFax(dto.getOfficeFax());
		ser.setOfficePhone(dto.getOfficePhone());
		ser.setEmail(dto.getEmail());
		ser.setAddress(dto.getAddress());
		ser.setOrgType("services");
		if (dto.getParentOrgNo() != null) {
			Organization org = organizationDAO.findById(dto.getParentOrgNo());

			if (org.getOrgType() == "services" || org.getOrgType() == "company") {

				ser.setParentOrg(org);
			} else {

				throw new ApplicationException("ERROR_PARENT_MUST_BE_SERVICE_OR_COMPANY\n");
			}
		}

		// 关联负责
		if (dto.getPersonInChargeName() != null) {
			ser.setPersonInCharge(userDAO.findUniqueBy("fullName", dto.getPersonInChargeName()));
		}

		// 关联负责
		if (dto.getPersonInChargeNo() != null) {
			ser.setPersonInCharge(userDAO.findById(dto.getPersonInChargeNo()));
		}
		if(null != dto.getCompanyNo()){
			ser.setCompanyNo(dto.getCompanyNo());
		}
		organizationServicesDAO.save(ser);
		if(ser.getParentOrg()!=null){
			ser.setPath(ser.getParentOrg().getPath()+ser.getOrgNo()+"/");
		}else{
			ser.setPath(ser.getOrgNo()+"/");
		}
		// 设置工作时间
		ServiceTime st = new ServiceTime();
		st.setAllday(true);
		st.setFriday(true);
		st.setMonday(true);
		st.setThursday(true);
		st.setTuesday(true);
		st.setWednesday(true);
		st.setSaturday(false);
		st.setSunday(false);
		st.setStartHour(0);
		st.setStartMinute(0);
		st.setEndHour(0);
		st.setEndMinute(0);
		st.setOrganization(ser);
		serviceTimeDAO.save(st);

		dto.setOrgNo(ser.getOrgNo());
		ApplicationContext ctx = AppliactionBaseListener.ctx;
		if (ctx != null) {
			IBPS bps = (IBPS) ctx.getBean("bps");
			bps.createGroup("Group_" + ser.getOrgNo(), "Group_" + ser.getParentOrg().getOrgNo());
		}

	}

	/**
	 * 修改服务机构.
	 * 
	 * @param dto
	 *            机构数据DTO：OrganizationDTO
	 */
	@Transactional()
	public void mergeOrganizationServices(OrganizationDTO dto) {
		OrganizationServices ser = organizationServicesDAO.findById(dto.getOrgNo());

		ser.setOrgName(dto.getOrgName());
		ser.setOfficeFax(dto.getOfficeFax());
		ser.setOfficePhone(dto.getOfficePhone());
		ser.setEmail(dto.getEmail());
		ser.setAddress(dto.getAddress());
		ser.setOrgType("services");
		if (dto.getParentOrgNo() != null && !dto.getOrgNo().equals(dto.getParentOrgNo())) {

			ser.setParentOrg(organizationDAO.findById(dto.getParentOrgNo()));

		} else {

			throw new ApplicationException("ERROR_PARENT_ORG_IS_SELF");

		}

		// 关联负责
		if (dto.getPersonInChargeName() != null) {
			ser.setPersonInCharge(userDAO.findUniqueBy("fullName", dto.getPersonInChargeName()));
		}

		// 关联负责
		if (dto.getPersonInChargeNo() != null) {
			ser.setPersonInCharge(userDAO.findById(dto.getPersonInChargeNo()));
		}

		// 机构角色
		Set<Role> roles = new HashSet<Role>();
		if (dto.getOrgRole() != null) {

			for (Long id : dto.getOrgRole()) {
				Role role = roleDAO.findById(id);
				roles.add(role);
			}
		}
		ser.setOrgRoles(roles);

		organizationServicesDAO.merge(ser);
		if(ser.getParentOrg()!=null){
			ser.setPath(ser.getParentOrg().getPath()+ser.getOrgNo()+"/");
		}else{
			ser.setPath(ser.getOrgNo()+"/");
		}
	}

	/**
	 * 批量删除服务机构.
	 * 
	 * @param orgNos
	 *            机构编号数组：Long [] orgNos
	 */
	@Transactional()
	public void deleteOrganizationServices(Long[] orgNos) {
		organizationServicesDAO.deleteByIds(orgNos);
	}

	/**
	 * 根据ID查找服务机构.
	 * 
	 * @param id
	 *            服务机构编号：Long id
	 * @return 服务机构 OrganizationServices
	 */
	public OrganizationServices findOrganizationServicesById(Long id) {
		return organizationServicesDAO.findById(id);
	}

	/**
	 * 根据编号查找机构DTO.
	 * 
	 * @param id
	 *            机构编号：Long id
	 * @return OrganizationDTO
	 */
	public OrganizationDTO findById(Long id) {
		OrganizationDTO dto = new OrganizationDTO();
		OrganizationServices entity = organizationServicesDAO.findById(id);
		if (entity != null) {
			OrganizationDTO.entity2dto(entity, dto);
			if (entity.getParentOrg() != null) {
				dto.setParentOrgNo(entity.getParentOrg().getOrgNo());
			}
		}

		return dto;

	}

}
